<script setup>
import { Chart } from '@antv/g2'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  ready: {
    type: Boolean,
    default: false,
  },
})

let chartInstance = null
const chartDomRef = ref(null)
const chartPanelRef = ref(null)

const state = reactive({
  isInited: false,
})

// 初始化渲染图表
const createChartView = (container, { height }) => {
  const chart = new Chart({
    container,
    autoFit: true,
    height: height || 173,
    marginLeft: -12,
    marginTop: -6,
  })

  const title = `${new Date().getFullYear()}年度按月份统计订单数`

  chart
    .data(props.data.orderList)
    .encode('x', 'month')
    .encode('y', 'orderNum')
    .scale('x', {
      range: [0, 1],
    })
    .scale('y', {
      nice: true,
    })
    .axis('x', {
      title: false,
      labelFormatter: val => `${val}月`,
    })
    .axis('y', {
      title: '(总量)',
      labelFilter: (datum, idx) => idx % 2 === 0,
      gridFilter: (datum, idx) => idx % 2 === 0,
    })
    .title({
      subtitle: title,
      size: 12,
    })
    .theme({ type: 'custom' })

  chart.line().encode('shape', 'smooth')
    .tooltip({
      title: d => `${d.month}月`,
      items: [{ name: '订单数', channel: 'y' }],
    })
    .style({
      lineWidth: 3,
      stroke: '#FFD15C',
    }).animate({
      enter: {
        type: 'scaleInX',
        duration: 300,
        delay: 100,
      },
    })
  chart.render()

  state.isInited = true

  return chart
}

// 更新图表数据
const updateChartView = (chart) => {
  chart.changeData(props.data.orderList)

  // 重新渲染
  chart.render()
}

watch([() => props.data, () => props.ready], ([newData, newReady]) => {
  if(state.isInited && chartInstance) {
    // 已经初始化过图表, 直接更新数据
    // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '更新图表数据', newData)
    updateChartView(chartInstance)
  }
  else {
    // 查看数据接口是否已经准备好
    if(props.ready || newReady) {
      if(newData?.orderList && chartDomRef.value) {
        // 请求数据成功, 初始化图表
        const { width, height } = chartDomRef.value.getBoundingClientRect()
        chartInstance = createChartView(chartDomRef.value, { width, height })
        // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '初始化图表', newData)
      }
      else {
        // 图标数据为空，更新初始化状态, 展示缺省空状态
        state.isInited = true
        // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '图表数据为空')
      }
    }
    else {
      // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '等待数据请求完成', newData)
    }
  }
}, { deep: true, immediate: true })
</script>

<template>
  <section ref="chartPanelRef" class="chart-order-stats">
    <div class="quick-view">
      <div class="quick-view__item day">
        <span>今日订单</span>
        <span>{{ data.todayNum || 0 }}</span>
      </div>
      <div class="quick-view__item month">
        <span>本月订单</span>
        <span>{{ data.monthNum || 0 }}</span>
      </div>
      <div class="quick-view__item year">
        <span>本年订单</span>
        <span>{{ data.yearNum || 0 }}</span>
      </div>
    </div>
    <div ref="chartDomRef" class="panel-layout panel-layout--chart" />
  </section>
</template>

<style lang='scss' scoped>
.chart-order-stats {
  height: 100%;
  padding: 16px 0;

  .quick-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 32px;
    padding: 0 20px;
    background: rgb(158 225 255 / 6%);
    border: 0.5px solid rgb(0 157 227 / 40%);
    border-radius: 2px;
    box-shadow: 0 0 4px 0 rgb(197 255 251 / 25%) inset;

    &__item {
      display: flex;
      align-items: center;

      &::before {
        display: inline-block;
        width: 14px;
        height: 14px;
        content: '';
      }

      span {
        margin-left: 10px;
        font-size: 14px;

        &:last-child {
          color: $chart-cyan;
        }
      }

      &.day {
        &::before {
          background-color: $chart-cyan;
        }

        span {
          &:last-child {
            color: $chart-cyan;
          }
        }
      }

      &.month {
        &::before {
          background-color: $chart-yellow;
        }

        span {
          &:last-child {
            color: $chart-yellow;
          }
        }
      }

      &.year {
        &::before {
          background-color: $chart-blue;
        }

        span {
          &:last-child {
            color: $chart-blue;
          }
        }
      }
    }
  }
}

.panel-layout {
  &--chart {
    display: flex;
    width: 100%;
    height: calc(100% - 32px);
    margin-top: 16px;
    transform: translateX(-5px);
  }
}
</style>
